<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class CAjaxController extends CController
{
	public $layout='//layouts/ajax';
	public $result_ids = array();
	protected $_result = array();

	public function init() {
		$this->result_ids = getParam('result_ids') ? explode(',', getParam('result_ids')) : array();
	}

	public function getOutput($view, $data) {
		return $this->renderPartial($view, $data, true);
	}

	public function ajaxResponse($html) {
		$text = $html;

		if ( !empty($this->result_ids) ) {
			foreach ($this->result_ids as $r_id) {
				if (strpos($text, ' id="' . $r_id . '">') !== false) {
					$start = strpos($text, ' id="'.$r_id.'">') + strlen(' id="' . $r_id . '">');
					$end = strpos($text, '<!--' . $r_id . '--></');
					$this->assignHtml($r_id, substr($text, $start, $end - $start));
				// Assume that all data should be put to div with this ID
				}
			}
			$text = '';
		}

		session_write_close();

		$response = CJSON::encode(array(
			'text' => trim($text),
			'data' => $this->_result
		));

		echo $response;

		app()->end();
	}

	public function assignHtml($r_id, $text) {
		$this->_result['html'][$r_id] = $text;
	}

	public function assignVar($var, $value) {
		$this->_result[$var] = $value;
	}
}